%{
	
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#include "StateAction.h"
#include "MTparser.h"


static 	TuringMachine * TM;
static	int line;

char * deleteSpaces(char * src, int srcSize) {
	int i;
	char * out = (char *)malloc(sizeof(char) * srcSize);
	int outSize=0;	

	// Get rid of spaces
	for(i=0;i<srcSize && src[i] != '\0';i++)
		if(src[i] != ' ' && src[i] != '\t')
			out[outSize++]=src[i];
	
	// Resize it and return
	out = (char *)realloc(out, outSize);
	out[outSize]='\0';
	return out;
}

char * substrchr(char * src, char chr){
	int outSize=strchr(src,chr)-src+1;
	char * out=(char *)malloc(sizeof(char) * outSize);

	strncpy(out,src,outSize-1);
	out[outSize-1]='\0';
	return out;
}

	
%}

estado [A-Za-z0-9!]+
simbolo [0-2]
accion[0-2><]
spaces [" "\t]*


%option noyywrap
%%


{spaces}{estado}{spaces}[,]{spaces}{simbolo}{spaces}[,]{spaces}{estado}{spaces}[,]{spaces}{accion}{spaces}[\n]? { 
			yytext[yyleng]='\0';
			char * tmp = deleteSpaces(yytext,yyleng+1);
			char * estado1=substrchr(tmp,',');
			tmp=strchr(tmp,',')+1;
			char * simbolo=substrchr(tmp,',');
			tmp=strchr(tmp,',')+1;
			char * estado2=substrchr(tmp,',');
			tmp=strchr(tmp,',')+1;
			char * accion;
			if(strchr(tmp,'\n')!=NULL)
				accion=substrchr(tmp,'\n');
			else
				accion=substrchr(tmp,'\0');

			if(TM==NULL){
 				TM=new TuringMachine(estado1);
			}else{
				TM->addState(estado1);
			}
			TM->addState(estado2);
			StateAction * acc;
			switch(*accion){
				case '0':
					acc= new StateAction(0);
					break;
				case '1':
					acc= new StateAction(1);
					break;
				case '2':
					acc= new StateAction(2);
					break;
				case '<':
					acc= new StateAction(StateAction::LEFT);
					break;
				case '>':
					acc= new StateAction(StateAction::RIGHT);
					break;
			}
			TM->addStateAction(estado1, estado2, *simbolo-'0', acc);
			line++;
		}


.	{
	return line;
	}
\n 	{
		line++;
	}

%%


TuringMachine * parseTM(FILE * Machine){
	TM=NULL;
	line=1;
 	yyin = Machine;
	int errorLine=yylex();
	if(errorLine){
		fprintf(stderr,"Error en la linea %d del archivo.\n",errorLine==1?1:errorLine-1);
		return NULL;
	}
	return TM;
}
